package cn.qn.common.configs;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;

/**
 * @author: Bryant
 * @date: 2019/1/29
 * @description:
 */
@Slf4j
public class ResetTemplateRequestInterceptor implements ClientHttpRequestInterceptor {
    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        traceRequest(request, body);
        ClientHttpResponse response = execution.execute(request, body);
        traceResponse(response);
        return response;
    }

    private void traceRequest(HttpRequest request, byte[] body) throws IOException {
        JSONObject logs=new JSONObject();
        logs.put("url",request.getURI());
        logs.put("method",request.getMethod());
        logs.put("headers", request.getHeaders());
        logs.put("token",request.getHeaders());
        logs.put("body",new String(body, "UTF-8"));
        log.info(logs.toString());
    }

    private void traceResponse(ClientHttpResponse response) throws IOException {
        JSONObject logs=new JSONObject();
        logs.put("StatusCode",response.getStatusCode());
        logs.put("StatusText",response.getStatusText());
        logs.put("Headers", response.getHeaders());
        log.info(logs.toString());
    }
}
